import 'package:collection/src/iterable_extensions.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_xxyk/model/user_info.dart';
import 'package:flutter_xxyk/util/image_picker.dart';
import 'package:get_it/get_it.dart';

class ProfileDetail extends StatefulWidget {
  const ProfileDetail({Key? key}) : super(key: key);

  @override
  _ProfileDetailState createState() => _ProfileDetailState();
}

class _ProfileDetailState extends State<ProfileDetail> {
  final Dio dio = GetIt.I<Dio>();

  UserInfo? userInfo;

  bool _isLoading = false;

  final List<Map<String, dynamic>> genderList = const [
    {
      "title": "保密",
      "value": 0,
    },
    {
      "title": "男",
      "value": 1,
    },
    {
      "title": "女",
      "value": 2,
    }
  ];

  String findGenderByVal(int? val) {
    return genderList.firstWhereOrNull((i) => i["value"] == val)!["title"];
  }

  int? gender;

  DateTime? birthDate;

  @override
  void initState() {
    getUserInfo();
    super.initState();
  }

  Future<void> getUserInfo() async {
    _isLoading = true;
    final res = await dio.get("/h5/learner/info");
    final data = UserInfo.fromJson(res.data["data"]);
    setState(() {
      userInfo = data;
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("个人资料"),
      ),
      body: _isLoading
          ? Center(
              child: SpinKitPulse(
                color: Theme.of(context).colorScheme.secondary,
                size: 50.0,
              ),
            )
          : SingleChildScrollView(
              child: Column(
                children: [
                  _buildRow(
                    "头像",
                    onTap: () => _showAvatarPicker(context),
                    trailing: Row(
                      children: [
                        SizedBox(
                          width: 50,
                          height: 50,
                          child: CircleAvatar(
                            backgroundImage: (userInfo!.avatar == null
                                ? AssetImage('assets/images/avatar.png')
                                : NetworkImage(
                                    userInfo!.avatar,
                                  ) as ImageProvider),
                          ),
                        ),
                      ],
                    ),
                  ),
                  _divider(),
                  _buildRow("昵称", trailing: Text(userInfo!.nickname!)),
                  _divider(),
                  _buildRow(
                    "性别",
                    onTap: () => _showGenderPicker(context),
                    trailing: userInfo!.gender == null
                        ? Text("未知")
                        : Text(findGenderByVal(userInfo!.gender)),
                  ),
                  _divider(),
                  _buildRow(
                    "生日",
                    onTap: () => _showDatePicker(context),
                  ),
                ],
              ),
            ),
    );
  }

  Widget _buildRow(String label,
      {Widget? trailing, GestureTapCallback? onTap}) {
    return Ink(
      child: InkWell(
        onTap: onTap,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                label,
                style: TextStyle(
                  fontSize: 18,
                  color: Color(0xff323233),
                ),
              ),
              Row(
                children: [
                  if (trailing != null) trailing,
                  if (onTap != null) ...[
                    SizedBox(
                      width: 10,
                    ),
                    Icon(
                      Icons.arrow_forward_ios_outlined,
                      size: 16,
                      color: Color(0xff969799),
                    )
                  ]
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _divider() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: Divider(),
    );
  }

  Future<void> _showAvatarPicker(BuildContext context) async {
    ImagePickerUtil.displayPickImageDialog(context, (picker, source) async {
      final pickedFile = await picker.pickImage(
        source: source,
      );
      if (pickedFile != null) {
        print(pickedFile.path);
      }
    });
  }

  void _showDatePicker(ctx) {
    showCupertinoModalPopup(
        context: ctx,
        builder: (_) => Container(
              height: 400,
              color: const Color.fromARGB(255, 255, 255, 255),
              child: Column(
                children: [
                  SizedBox(
                    height: 300,
                    child: CupertinoDatePicker(
                        mode: CupertinoDatePickerMode.date,
                        initialDateTime: DateTime.now(),
                        onDateTimeChanged: (val) {
                          setState(() {
                            birthDate = val;
                          });
                        }),
                  ),

                  // Close the modal
                  CupertinoButton(
                    child: const Text('确认'),
                    onPressed: () => Navigator.of(ctx).pop(),
                  )
                ],
              ),
            ));
  }

  void _showGenderPicker(ctx) {
    int? _position;
    showCupertinoModalPopup(
        context: ctx,
        builder: (_) => Container(
              height: 250,
              color: const Color.fromARGB(255, 255, 255, 255),
              child: Column(
                children: [
                  SizedBox(
                    height: 160,
                    child: CupertinoPicker(
                      itemExtent: 50,
                      children:
                          genderList.map((i) => Text(i['title'])).toList(),
                      onSelectedItemChanged: (position) {
                        _position = position;
                      },
                    ),
                  ),
                  // Close the modal
                  CupertinoButton(
                    child: const Text('确认'),
                    onPressed: () {
                      setState(() {
                        userInfo!.gender = _position;
                      });
                      Navigator.of(ctx).pop();
                    },
                  )
                ],
              ),
            ));
  }
}
